/**
 * 114静态分析报告
 *
 * Created by nonzhizhong on 2024/06/03.
 */
const fs = require('fs-extra');
const path = require('path');
const compressing = require('compressing');

const defects = require('../../../defects');
const BaseReporter = require('./../base-report');
// 导出报告的分类
const exportReportCategory = {
  file: 1, // 按文件分类
  ruleSet: 2, // 按规则集分类
};
const split = false;
class StaticAnalyze114Reporter extends BaseReporter {
  constructor(versionId, locale, version = null, project = null, creator = null, outputDir = null, format, filters = {},
    reportCategory = exportReportCategory.file, baseDir = null, reportRange = null) {
    super(versionId, locale, version, project, creator, outputDir, baseDir || __dirname, format);
    this.filters = filters;
    this.ableReportCategory = parseInt(reportCategory, 10) === exportReportCategory.ruleSet;
    this.reportRange = reportRange;
    this.filesRules = [];
    this.versionDir = null;
  }

  /**
   * 报告生成
   */
  async generate(progressIndicator) {
    const result = {
      cachePath: this.outputDir,
    };
    if (this.ableReportCategory) {
      return Promise.resolve();
    }
    const [filesProgressIndicator, generateReportProgressIndictor] = progressIndicator ? progressIndicator.split([0.9, 0.1]) : [null, null];
    const { versionPath } = await this.spliteByProjectVersion();
    this.versionDir = path.join(versionPath, `${this.project.projectName}项目测试问题单`);
    await this.spliteByFile(null, filesProgressIndicator);
    if (split) {
      await fs.ensureDir(this.versionDir);
    } else {
      await this.generateReport('file-template', { files: this.filesRules, versionName: this.version.versionName }, this.versionDir);
    }
    const fileName = `${this.project.projectName}-${this.version.versionName}-${this.getReportName()}-${this.format}.zip`;
    result.reportPath = path.join(this.outputDir, fileName);
    const reportsDir = path.join(this.outputDir, this.project.projectName);
    if (generateReportProgressIndictor) {
      generateReportProgressIndictor.finish();
    }
    await compressing.zip.compressDir(reportsDir, result.reportPath);
    return result;
  }

  /**
   * 处理单个文件，生成缺陷报告
   * @param {Object}} file 单个文件信息
   * @returns {Promise}
   */
  async handleFile(file) {
    const { _id: fileId, fileName } = file;
    const fileAllDefects = await defects.getDefects(
      this.versionId,
      {
        fileId,
        ruleSets: this.filters.ruleSets,
        levels: this.filters.levels,
        status: this.filters.defectStatus,
      }
    );
    const rulesMap = new Map();
    if (fileAllDefects.length === 0) {
      return;
    }
    fileAllDefects.forEach((defect) => {
      const ruleId = defect.ruleId.toString();
      if (!rulesMap.has(ruleId)) {
        rulesMap.set(ruleId, { ruleName: defect.ruleName, lines: [] });
      }
      const line = defect.locations && defect.locations.begin && defect.locations.begin.line ? defect.locations.begin.line : '';
      const lineStr = `第${line}行`;
      if (rulesMap.get(ruleId).lines && !rulesMap.get(ruleId).lines.includes(lineStr)) {
        rulesMap.get(ruleId).lines.push(lineStr);
      }
    });
    const data = {
      fileName,
      rules: [...rulesMap.values()],
    };
    if (split) {
      const fileReportPath = path.join(this.versionDir, path.dirname(file.path), file.fileName);
      await fs.ensureDir(path.dirname(fileReportPath));
      await this.generateReport('file-template', { files: [data], versionName: this.version.versionName }, fileReportPath);
    } else {
      this.filesRules.push(data);
    }
  }
}
/**
 * Export model definition object.
 */

module.exports = StaticAnalyze114Reporter;
